# -*- coding: utf-8 -*-
import hashlib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'https://gateway.999pays.com/Pay/KDBank.aspx'
_QUERY_GATEWAY = 'https://gateway.999pays.com/Pay/Query.aspx'
# 支付方式微信wap,单笔限额（10---500）qqwap单笔限额（1---1000）可以对接。dwc
APP_CONF = {
    '1004112': {
        'API_KEY': '7211b0818da24802aed9bbe50cacbd36',
    },
    '1004335': {
        'API_KEY': '795d59e07e8c482380ecc322202f49aa',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_pay_type(service):
    if service == 'alipay':
        return '36'
    elif service == 'wxpay':
        return '33'
    elif service == 'qq':
        return '92'
    elif service == 'jd':
        return '98'
    else:
        # return '31'  # quick
        return '32'  # quick


def generate_sign(d, key):
    '''  生成下单签名 '''
    s = '{}|{}|||{}|{}|{}'.format(
        d['P_UserID'], d['P_OrderID'], d['P_FaceValue'], d['P_ChannelID'], key
    )
    _LOGGER.info("huitianpay sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest().lower()
    return sign


def generate_notify_sign(d, key):
    '''  生成下单签名 '''
    # P_UserId | P_OrderId | P_CardId | P_CardPass | P_FaceValue | P_ChannelId | P_PayMoney | P_ErrCode | Key
    s = '{}|{}|||{}|{}|{}|{}|{}'.format(
        d['P_UserId'], d['P_OrderId'], d['P_FaceValue'], d['P_ChannelId'], d['P_PayMoney'], d['P_ErrCode'], key
    )
    _LOGGER.info("huitianpay notify sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest().lower()
    return sign


def generate_query_sign(d, key):
    '''  生成下单签名 '''
    s = 'P_UserId={}&P_OrderId={}&P_ChannelId={}&P_CardId=&P_FaceValue={}&P_PostKey={}'.format(
        d['P_UserID'], d['P_OrderID'], d['P_ChannelID'], d['P_FaceValue'], key
    )
    _LOGGER.info("huitianpay query sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params['P_PostKey']
    params.pop('P_PostKey')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("huitianpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def build_form(params):
    html = u"<head><title>loading...</title></head><form id='yiaipaysubmit' name='yiaipaysubmit' action='" + _GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['yiaipaysubmit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('P_UserID', app_id),
        ('P_OrderID', str(pay.id)),
        ('P_CardId', ''),
        ('P_CardPass', ''),
        ('P_Price', pay_amount),
        ('P_FaceValue', pay_amount),
        ('P_ChannelID', _get_pay_type(service)),
        ('P_Result_URL', '{}/pay/api/{}/huitianpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('P_Notify_URL', '{}/pay/api/{}/huitianpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['P_PostKey'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("huitianpay create  data: %s, url: %s", parameter_dict, _GATEWAY)
    html_text = build_form(parameter_dict)
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id, }


# ErrCode=0 ProcessError
def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("huitianpay notify data1: %s", data)
    _LOGGER.info("huitianpay notify body: %s", request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['P_OrderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('huitianpay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['P_ErrCode'])
    trade_no = ''
    total_fee = float(data['P_PayMoney'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '0':
        _LOGGER.info('huitianpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('P_UserID', app_id),
        ('P_OrderID', str(pay_id)),
        ('P_CardId', ''),
        ('P_CardPass', ''),
        ('P_FaceValue', '%.2f' % pay_order.total_fee),
        ('P_ChannelID', _get_pay_type(pay_order.service)),
    ))
    parameter_dict['P_PostKey'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info("huitianpay query  data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_QUERY_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("huitianpay query  rsp data: %s", response.text)
    if response.status_code == 200:
        trade_status = _get_str(response.text, '&P_status=', '&')
        trade_no = _get_str(response.text, '&P_OrderId=', '&')
        total_fee = float(_get_str(response.text, '&P_payMoney=', '&'))

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '1':
            _LOGGER.info('huitianpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('huitianpay data error, status_code: %s', response.status_code)
